/**
 * log4js日志管理封装
 * @author 阿逼
 * @date 2021-08-01
 */

const log4js = require('log4js')
const logModel = require('./../modules/LogSchema')
// 级别常量定义
const levels = {
  trace: log4js.levels.TRACE,
  debug: log4js.levels.DEBUG,
  info: log4js.levels.INFO,
  warn: log4js.levels.WARN,
  error: log4js.levels.ERROR,
  fatal: log4js.levels.FATAL,
}
// 配置log4js
log4js.configure({
  appenders: {
    // 控制台输出
    console: { type: 'console' },
    // info
    info: {
      type: 'file',
      filename: 'logs/log.log',
    },
    error: {
      type: 'file',
      filename: 'logs/err',
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true, // 设置文件名为 filename +  pattern
    },
    mark: {
      type: 'file',
      filename: 'logs/下载日志',
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true, // 设置文件名为 filename +  pattern
    },
    fatal: {
      type: 'file',
      filename: 'logs/还单日志',
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true, // 设置文件名为 filename +  pattern
    },
  },
  categories: {
    // 默认日志，输出debug 及以上级别的日志
    default: {
      appenders: ['console'],
      level: 'debug',
    },
    // 错误日志，输出error 及以上级别的日志
    error: {
      appenders: ['error', 'console'],
      level: 'error',
    },
    info: {
      appenders: ['info', 'console'],
      level: 'error',
    },
    mark: {
      appenders: ['mark'],
      level: 'error',
    },
    fatal: {
      appenders: ['fatal'],
      level: 'error',
    },
  },
})

/**
 * 日志输出,level为debug
 * @param {String} content
 */
exports.debug = (content) => {
  let logger = log4js.getLogger('error')
  logger.level = levels.debug
  logger.debug(content)
}

/**
 * 日志输出,level为error
 * @param {String} content
 */
exports.error = (content) => {
  ;(async () => {
    await logModel.create({ type: 2, content: content })
  })()
  let logger = log4js.getLogger('error')
  logger.level = levels.error
  logger.error(content)
}

/**
 * 日志输出,level为info
 * @param {String} content
 */
exports.info = (content) => {
  ;(async () => {
    await logModel.create({ type: 1, content: content })
  })()
  let logger = log4js.getLogger('info')
  logger.level = levels.info
  logger.info(content)
}

/**
 * 下载日志输出,level为info
 * @param {String} content
 */
exports.mark = (content) => {
  ;(async () => {
    await logModel.create({ type: 4, content: content })
  })()
  let logger = log4js.getLogger('mark')
  logger.level = levels.info
  logger.mark(content)
}

/**
 * 还单日志输出 level为info
 */
exports.fatal = (content) => {
  ;(async () => {
    await logModel.create({ type: 3, content: content })
  })()
  let logger = log4js.getLogger('fatal')
  logger.level = levels.info
  logger.fatal(content)
}
